/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ifconnect.model.dao;

import ifconnect.model.entity.Disciplina;
import ifconnect.model.entity.Usuario;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.persistence.Query;

/**
 *
 * @author Genemes
 */
public class DisciplinaDao extends DaoGenerico implements Serializable {

    public DisciplinaDao() {
        super();
    }
    
    public boolean cadastroDisciplina(Disciplina disciplina) {
        try {
            this.salvar(disciplina);
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            this.getEntityManager().getTransaction().rollback();
            return false;
        }
    }

    public boolean excluirDisciplina(Long id) {
        Disciplina d = null;
        try {
            d = this.buscar(Disciplina.class, id);
            this.remover(d);
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            this.getEntityManager().getTransaction().rollback();
            return false;
        }
    }
    
    public List<Disciplina> listar(){
        List<Disciplina> listaDisciplinas = new ArrayList<Disciplina>();
        listaDisciplinas = this.listarTodos(Disciplina.class);
        return listaDisciplinas;
    }
    
    public List<Disciplina> listarSemProfessor(){
        List<Disciplina> listaDisciplinas = new ArrayList<Disciplina>();
        listaDisciplinas = this.listarTodos(Disciplina.class);
        
        List<Disciplina> listaDisciplinasSemProfessor = new ArrayList<Disciplina>();
        for (Iterator<Disciplina> it = listaDisciplinas.iterator(); it.hasNext();) {
            Disciplina disciplina = it.next();
            if(disciplina.getProfessor() == null){
                listaDisciplinasSemProfessor.add(disciplina);
            }
        }
        return listaDisciplinasSemProfessor;
    }
    
    public List<Disciplina> listarPorProfessor(Usuario professor){
        List<Disciplina> disciplinas = null;
        this.getEntityManager().getTransaction().begin();

        try{
            Query q = this.getEntityManager().createQuery("select d from Disciplina d where d.professor = :pf");
            q.setParameter("pf", professor);
            disciplinas = (List<Disciplina>) q.getResultList();
            this.getEntityManager().getTransaction().commit();
            return disciplinas;
        } catch (Exception ex){
            ex.printStackTrace();
            this.getEntityManager().getTransaction().rollback();
            return null;
        }
    }
}
